package com.powermgr.boringtest.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.powermgr.boringtest.utils.ConfigUtils.*;

/**
 * InitUtils
 *
 * @author qiuxiangdong
 * @date 2023/9/18 18:59
 */
@Log4j2
public class InitUtils {

    private static List<Map<String, Map<String, List<String>>>> getCase() {
        try {
            String caseStr = ReadWriteUtils.readFile(CASE_JSON);
            return JSON.parseObject(caseStr, List.class);
        } catch (IOException e) {
            log.error("获取 Case.json 失败", e);
            return null;
        }
    }

    public static List<String> getCaseValue(String type, String modules) {
        final List<String>[] value = new List[]{null};
        for (Map<String, Map<String, List<String>>> map : getCase()) {
            Map<String, List<String>> ut = map.get(type);
            if (ut != null){
                Set<Map.Entry<String, List<String>>> set = ut.entrySet();
                set.forEach(entry ->{
                    if (entry.getKey().equals(modules)){
                        value[0] = entry.getValue();
                    }
                });
            }
        }
        return value[0];
    }

    private static List<Map<String, Map<String, String>>> getCi() {
        try {
            String prBuildStr = ReadWriteUtils.readFile(CI);
            return JSON.parseObject(prBuildStr, List.class);
        } catch (IOException e) {
            log.error("获取 Ci.json 失败", e);
            return null;
        }
    }
 
    public static String getCiValue(String branch, String type) {
        final String[] name = {null};
        for (Map<String, Map<String, String>> map : getCi()) {
            Map<String, String> downloadType = map.get(branch);
            if (downloadType != null){
                Set<Map.Entry<String, String>> set = downloadType.entrySet();
                set.forEach(entry ->{
                    if (entry.getKey().equals(type)){
                        name[0] = entry.getValue();
                    }
                });
            }
        }
        return name[0];
    }

    private static Map<String, String> getUser() {
        try {
            String emailStr = ReadWriteUtils.readFile(USER_JSON);
            return JSON.parseObject(emailStr, Map.class);
        } catch (IOException e) {
            log.error("获取 User.json 失败", e);
            return null;
        }
    }

    public static String getUserValue(String key) {
        String[] value = {null};
        Set<Map.Entry<String, String>> set = getUser().entrySet();
        set.forEach(entry ->{
            if (entry.getKey().equals(key)){
                value[0] = entry.getValue();
            }
        });
        return value[0];
    }
}
